<template>
  <div class="app-container">
    <!-- 搜索 -->
    <el-card>
      <el-form :inline="true" :model="listQuery" size="small">
        <el-form-item>
          <el-input
            placeholder="商家名称"
            clearable
            v-model="listQuery.name"
            @keyup.enter.native="handleFilter"
          />
        </el-form-item>
        <el-form-item>
          <el-select
            size="small"
            v-model="listQuery.category"
            clearable
            placeholder="商品分类"
          >
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click.native="handleFilter"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >
            新增{{ title }}
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="handleBatchDelete"
          >
            批量删除
          </el-button>
        </el-form-item>
      </el-form>

      <!-- table列表 -->
      <el-table
        style="width: 100%"
        border
        stripe
        size="small"
        :data="datas"
        v-loading="listLoading"
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <el-table-column label="#" align="center" type="selection" />
        <el-table-column
          v-for="column in tableColumns"
          :key="column.key"
          :label="column.title"
          :prop="column.key"
          :align="column.align ? column.align : 'center'"
          :width="column.width ? column.width : ''"
        >
        </el-table-column>
        <el-table-column align="center" label="操作" width="180px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="handleEdit(scope)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="handleDelete(scope)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getGoodsList"
      />
    </el-card>
    <!-- 弹框 -->
    <el-dialog :title="getTitle" :visible.sync="dialogVisible" width="55%">
      <el-form
        size="small"
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="120px"
        label-position="right"
        style="width: 95%"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="form.name" placeholder="商品名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品SN" prop="sn">
              <el-input v-model="form.sn" placeholder="商品SN" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品分类" prop="category">
              <el-select
                v-model="form.category"
                placeholder="商品分类"
                clearable
              >
                <el-option
                  v-for="item in categories"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品价格" prop="price">
              <el-input v-model="form.price" placeholder="商品SN" clearable>
                <el-button slot="append" type="default">元</el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="库存量" prop="stock_nums">
              <el-input
                v-model="form.stock_nums"
                placeholder="商品库存"
                clearable
              >
                <el-button slot="append" type="default">件</el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否下架" prop="drop">
              <el-select v-model="form.drop" placeholder="是否下架">
                <el-option
                  v-for="item in drops"
                  :label="item.label"
                  :value="item.value"
                  :key="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="顺序" prop="sort">
              <el-input v-model="form.sort" placeholder="顺序" clearable>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSave(false)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import Pagination from "@/components/Pagination";
import { pickerOptions } from "@/utils/const";

import {
  getGoodsList,
  addGoods,
  updateGoods,
  delGoods,
  delMultiGoods,
  getCategories,
} from "@/api/shopping";

const defaultForm = {
  id: null,
  name: null,
  sn: null,
  category: null,
  price: "",
  content: null,
  stock_nums: "",
  is_new: "",
  is_hot: "",
  catclick_nums: 0,
  drop: 0,
  sort: 0,
  user: null,
};

export default {
  name: "Goods",
  data() {
    return {
      form: Object.assign({}, defaultForm),

      formRules: {
        name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
        category: [{ required: true, message: "请商品分类", trigger: "blur" }],
        price: [{ required: true, message: "请输入商品价格", trigger: "blur" }],
        stock_nums: [
          { required: true, message: "请输入库存量", trigger: "blur" },
        ],
      },
      title: "商品",
      dialogType: "new",
      dialogVisible: false,
      categories: [],
      datas: [],
      selections: [],

      listLoading: true,
      listQuery: {
        name: null,
        category: null,
        page: 1,
        page_size: 15,
      },
      total: 0,

      tableColumns: [
        {
          key: "sn",
          title: "商品货号",
          align: "center",
        },
        {
          key: "name",
          title: "商品名称",
          align: "left",
        },
        {
          key: "category_name",
          title: "分类",
        },
        {
          key: "price",
          title: "价格",
        },
        {
          key: "stock_nums",
          title: "库存量",
        },
        {
          key: "sort",
          title: "顺序",
        },
        {
          key: "drop_name",
          title: "状态",
        },
      ],
      drops: [
        { value: 0, label: "无" },
        { value: 1, label: "下架" },
      ],
      pickerOptions,
    };
  },
  components: {
    Pagination,
  },
  computed: {
    ...mapGetters(["uid"]),
    getTitle() {
      return this.dialogType == "new"
        ? `新增${this.title}`
        : `修改${this.title}`;
    },
  },
  created() {
    this.getGoodsList();
    this.getCategoryList();
  },
  methods: {
    number() {
      this.form.price = this.form.merit.replace(/[^\d.]/g, "");
    },
    //商品分类
    getCategoryList() {
      getCategories()
        .then((res) => {
          this.categories = res;
        })
        .catch((error) => {
          console.log(error.message);
        });
    },

    //
    getGoodsList() {
      this.listLoading = true;
      getGoodsList(this.listQuery)
        .then((res) => {
          this.datas = res.results;
          this.total = res.count;
          this.listLoading = false;
        })
        .catch((err) => {
          this.listLoading = false;
          this.$message.error("获取数据失败!");
        });
    },

    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.getGoodsList();
    },
    //添加
    handleAdd() {
      // this.dialogVisible = true;
      // this.dialogType = "new";
      // this.form = Object.assign({}, defaultForm);
      // this.$nextTick(() => {
      //   this.$refs.formRef.clearValidate();
      // });
      this.$router.push("/shopping/goods_add");
    },
    //修改
    handleEdit(scope) {
      // this.dialogType = "edit";
      // this.form = scope.row;
      // this.dialogVisible = true;
      // this.$nextTick(() => {
      //   this.$refs.formRef.clearValidate();
      // });
      const goods_id = scope.row.id;
      this.$router.push(`/shopping/goods/${goods_id}`);
    },
    //保存
    async handleSave() {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        let res = null;
        if (this.dialogType == "new") {
          this.form.user = this.uid;
          try {
            res = await addGoods(this.form);
          } catch (err) {
            this.$message.error("增加失败!");
          }
        } else {
          if (!this.form.user) {
            this.form.user = this.uid;
          }
          try {
            res = await updateGoods(this.form);
          } catch (err) {
            // console.log(err);
            this.$message.error("修改失败!");
          }
        }

        this.dialogVisible = false;
        this.getGoodsList();

        const { name, category_name, price } = res;

        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>商品名称: ${name}</div>
              <div>商品分类: ${category_name}</div>
              <div>商品价格: ${price}</div>
            `,
          type: "success",
        });
      });
    },
    //弹窗显示，数据回显

    //删除数据
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delGoods(row.id);
          this.datas.splice($index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },
    handleBatchDelete() {
      if (this.selections.length == 0) {
        this.$message.warning("请选择要删除记录");
        return;
      }
      this.$confirm("确定要删除选中记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const sel_ids = {
            select_ids: this.selections,
          };
          const res = await delMultiGoods(sel_ids);
          this.getGoodsList();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },
    handleSelectionChange(val) {
      this.selections = val.map((item) => item.id);
    },
    // dataFormatter(row, column, cellValue, index) {
    //   if (column.property == "costs") {
    //     return cellValue && toThousandFilter(cellValue.toFixed(2));
    //   } else if (column.property == "quali_pay_fee") {
    //     return cellValue && cellValue.toFixed(2);
    //   } else if (column.property == "quali_recv_fee") {
    //     return cellValue && cellValue.toFixed(2);
    //   } else {
    //     return cellValue;
    //   }
    // },
    // getSummaries(param) {
    //   const { columns, data } = param;
    //   const sums = [];
    //   columns.forEach((column, index) => {
    //     if (index === 2) {
    //       sums[index] = "合计";
    //       return;
    //     }
    //     if (
    //       column.property === "costs" ||
    //       column.property === "quali_pay_fee" ||
    //       column.property === "quali_recv_fee"
    //     ) {
    //       const values = data.map((item) => item[column.property]);
    //       sums[index] = values
    //         .reduce((prev, curr) => {
    //           return prev + curr;
    //         }, 0)
    //         .toFixed(2);
    //       sums[index] = toThousandFilter(sums[index]);
    //       sums[index] += " 元";
    //     } else {
    //       return;
    //     }
    //   });

    //   return sums;
    // },
  },
};
</script>

<style scoped>
.el-pagination {
  margin-top: 20px;
}
</style>